package com.ruoyi.framework.config;

import org.apache.ibatis.reflection.MetaObject;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.domain.BaseEntity;

import cn.hutool.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;

/**
 * MP注入处理器
 * 
 * @author baize
 *
 */
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler
{

	@Override
	public void insertFill(MetaObject metaObject)
	{
		log.info("自动填充-新增");
		try
		{
			setFieldValByName(BaseEntity.CREATE_BY, getUsername(), metaObject);
			setFieldValByName(BaseEntity.CREATE_TIME, DateUtils.getNowDate(), metaObject);
		} catch (Exception e)
		{
			e.printStackTrace();
			throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_INTERNAL_ERROR);
		}
	}

	@Override
	public void updateFill(MetaObject metaObject)
	{
		log.info("自动填充-更新");
		try
		{
			setFieldValByName(BaseEntity.UPDATE_BY, getUsername(), metaObject);
			setFieldValByName(BaseEntity.UPDATE_TIME, DateUtils.getNowDate(), metaObject);
		} catch (Exception e)
		{
			e.printStackTrace();
			throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_INTERNAL_ERROR);
		}
	}

	private String getUsername()
	{
		try
		{
			return SecurityUtils.getUsername();
		} catch (Exception e)
		{
			log.error(e.getMessage(), e);
		}
		return null;
	}

}
